{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge，chrome=1">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta http-equiv="Cache-Control" content="max-age=7200" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>{% block title %}{% endblock %} - MrDoc</title>
    <link href="{% static 'layui/css/layui.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'editor.md/css/editormd.css' %}?version={{mrdoc_version}}" />
    <link href="{% static 'mrdoc.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <link rel="icon" href="{% static 'favicon_16.png' %}"/>
    <style>
        .markdown-body ul li{
            list-style:disc;
        }
        .markdown-body ul > li > ul > li{
            list-style-type: circle;
        }
        .markdown-body ol li{
            list-style-type: decimal;
        }
        .markdown-body ol ol ul,.markdown-body ol ul ul,.markdown-body ul ol ul,.markdown-body ul ul ul li{
            list-style-type: square;
        }
        .select-img-list{
            cursor: pointer;
            position: relative;
            display:flex;
            float: left;
            align-items:center;
            width: 120px;
            height:120px;
            margin: 0 20px 30px 0;
            text-align: center;
            overflow: hidden;
        }

        .select-img-list:hover{
            background-color: #EAFFEA;
        }
        .select-img-list-i{
            display: block;
            width: 100%;
            height: auto;
            -webkit-background-size: contain;
            border: 1px solid transparent;
            border-radius: 3px;
            overflow: hidden;
        }
    </style>
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
    {% block custom_style %}{% endblock %}


</head>
<body class="layui-container">
<!-- 页头 -->
{% include 'app_doc/head_base.html' %}
<!-- 页头结束 -->

<!-- 主体开始 -->
<div class="layui-container">
    {% block content %}
    {% endblock %}
</div>
<!-- 主体结束 -->

<script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script>
<script src="{% static 'layui/layui.all.js' %}"></script>
<script src="{% static 'editor.md/editormd.min.js' %}"></script>
<script>
    $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
        });
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;
    var laypage = layui.laypage;
    var md_changed = false; //初始化一个变量，用于判断编辑器是否修改
    //初始化editormd
    var editor = editormd("editor-md", {
        width       :   "100%",
        height      :   "1000px;",
        placeholder :   "开始使用Markdown书写MrDoc文档，编辑器支持以下功能：\n1.粘贴上传图片\n2.六级标题\n3.代码高亮\n4.本地图片和外链图片\n5.表格\n6.多级列表和任务列表\n7.Katex公式\n8.流程图\n9.时序图\n……",
        toolbarIcons : function() {
            return [
                "undo", "redo", "|",
                "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase","kaiSpan", "|",
                "h1", "h2", "h3", "h4", "h5", "h6", "|",
                "list-ul", "list-ol", "hr", "|",
                "link", "reference-link","imgUpload", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
                "watch", "preview", "|",
                "help"
            ]
        },
        //自定义工具栏添加楷体按钮
        toolbarIconTexts : {
            kaiSpan : "楷",
            imgUpload:'fa-image',
        },
        //自定义工具栏添加图片按钮
        toolbarIconsClass : {
            imgUpload:'fa-image',
        },
        //设置自定义工具栏按钮的事件
        toolbarHandlers : {
            /**
             * @param {Object}      cm         CodeMirror对象
             * @param {Object}      icon       图标按钮jQuery元素对象
             * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
             * @param {String}      selection  编辑器选中的文本
             */
            kaiSpan : function(cm, icon, cursor, selection) {
                //var cursor    = cm.getCursor();     //获取当前光标对象，同cursor参数
                //var selection = cm.getSelection();  //获取当前选中的文本，同selection参数
                // 替换选中文本，如果没有选中文本，则直接插入
                cm.replaceSelection('<span style="font-family:楷体">' + selection + "</span>");
                // 如果当前没有选中的文本，将光标移到要输入的位置
                if(selection === "") {
                    cm.setCursor(cursor.line, cursor.ch + 29);
                }
                // this == 当前editormd实例
                //console.log("testIcon =>", this, cm, icon, cursor, selection);
            },
            // 点击工具栏图片图标的响应函数 - 上传图片和选择图片
            imgUpload : function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:'1',
                    title:'添加图片',
                    area:['800px','600px'],
                    id:'uploadImg',//配置ID,
                    content:$('#upload-img'),
                })
            }
        },
        //设置语言
        lang : {
            toolbar : {
                kaiSpan : "添加楷体span标签",
                imgUpload:"添加图片到文档",
            }
        },
        //配置项
        pageBreak : true, //分页符
        path        :   "/static/editor.md/lib/",
        saveHTMLToTextarea : true,
        atLink      :   false,//禁用@链接
        tex         :   true,//开启科学公式
        tocm        :   true,//开启下拉目录
        taskList    :   true,//开启任务列表
        tocTitle    :   '文章导读',//目录标题
        tocContainer:   '',
        tocDropdown :   false,
        emoji       :   true,//开启Emoji
        flowChart   :   true, //开启流程图
        sequenceDiagram : true, //开启序列图
        imageUpload    : true, //开启图片上传
        htmlDecode     : "link,style,script,iframe|on*", //解析部分HTML标签
        imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL : "{% url 'upload_doc_img' %}",
        onchange:function(){
            md_changed = true
        },
    });
    //粘贴上传图片
    $("#editor-md").on('paste', function (ev) {
        var data = ev.clipboardData;
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.kind === 'file') {
                var blob = item.getAsFile();
                var reader = new FileReader();
                reader.onload = function (event) {
                    var base64 = event.target.result;
                    //ajax上传图片
                    $.post("{% url 'upload_doc_img' %}",{base:base64}, function (ret) {
                        layer.msg(ret.message);
                        if (ret.success === 1) {
                            //新一行的图片显示
                            editor.insertValue("\n![](" + ret.url + ")");
                        }
                    });
                }; // data url!
                var url = reader.readAsDataURL(blob);
            }
        }
    });
    //未保存离开提示
    window.onbeforeunload =function() {
    　　 if(md_changed){
            //console.log("页面未保存数据")
            return 1;
        }else{
            return null;
        }
    };
    //监听图片Tab选项卡切换
    element.on('tab(img-tab)', function(data){
      //console.log(this); //当前Tab标题所在的原始DOM元素
      //console.log(data.index); //得到当前Tab的所在下标
      //console.log(data.elem); //得到当前的Tab大容器
      if(data.index == 1){
        console.log('选择图片')
        $("#select-img-group").empty(); //删除已有分组按钮
        //请求新的分组数据
        $.post("{% url 'manage_img_group' %}",{'types':3},function(r){
            if(r.status){
                //console.log(r.data)
                group_btn_str = ''
                for(let i in r.data){
                    group_btn_str += '<button class="layui-btn layui-btn-normal" onclick="switchImgGroup(' + r.data[i].group_id +')">' + r.data[i].group_name + '(' + r.data[i].group_cnt + ')</button>'
                };
                $("#select-img-group").append(group_btn_str)
            }
        });
        //请求全部图片数据
        var loading = layer.load();
        $.post("{% url 'manage_image' %}",{'types':2,'group_id':0},function(r){
            if(r.status){
                //img_list_str = '<ul>'
                //for(let i in r.data){
                //    img_list_str += '<li class="select-img-list"><img class="select-img-list-i" src="' + r.data[i].path + '" title="' + r.data[i].name + '" /></li>'
                //}
                //img_list_str += '</ul>'
                //$("#select-img").append(img_list_str);
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length, //数据总数
                    limit:15, //单页数
                    jump: function(obj){
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function(){
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                            layui.each(thisData, function(index, item){
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                        return arr.join('');
                        }();
                    }
                });
                layer.close(loading);//关闭加载提示
            }else{
                layer.close(loading);
                layer.msg("获取图片失败")
            }
        })
      }
    });
    //插入选择的图片到编辑器
    insertImg = function(e){
        console.log(e.src);
        editor.insertValue("\n![](" + e.src + ")");
    };
    //切换图片分组
    switchImgGroup = function(e){
        var switch_loading = layer.load();
        $.post("{% url 'manage_image' %}", {
            'types': 2,
            'group_id': e
        },
        function(r) {
            if (r.status) {
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length,//数据总数
                    limit: 15,//单页数
                    jump: function(obj) {
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function() {
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr * obj.limit - obj.limit, obj.limit);
                            layui.each(thisData,
                            function(index, item) {
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                            return arr.join('');
                        } ();
                    }
                });
                layer.close(switch_loading); //关闭加载提示
            } else {
                layer.close(switch_loading);
                layer.msg("获取分组图片失败")
            }
        })
    }
</script>
<script src="{% static 'mrdoc.js' %}?version={{mrdoc_version}}"></script>
{% block custom_script %}
{% endblock %}
</body>
{% block custom_div %}
{% endblock %}
<div id="upload-img" style="display:none;margin:20px;">
    <div class="layui-tab" lay-filter="img-tab">
      <ul class="layui-tab-title">
        <li class="layui-this">上传图片</li>
        <li>选择图片</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <button class="layui-btn layui-btn-normal layui-btn-lg" id="upload_img">点击上传图片</button>
        </div>
        <div class="layui-tab-item">
            <div class="layui-row" id="select-img-group">
            </div><hr>
            <div class="layui-row" id="select-img"></div>
            <div id="select-img-page"></div>
        </div>
      </div>
    </div>
</div>
<script>
    //按钮选择上传图片
    var upload = layui.upload;
    upload.render({
        elem: '#upload_img',
        url: '{% url "upload_doc_img" %}',
        done: function(res, index, upload){ //上传后的回调
            //上传成功
            if(res.success == 1){
                editor.insertValue("\n![](" + res.url + ")");
                layer.closeAll();
                layer.msg("上传成功");
            }else{
                layer.msg("上传出错，请重试！")
            }
        },
        accept: 'images', //允许上传的文件类型
        acceptMime:'image/*',
        field:'manage_upload',
        size: 5000, //最大允许上传的文件大小

    })
</script>
</html>